package cn.harmonyoslearn.navrouter.listeners;

import cn.harmonyoslearn.navrouter.datas.NavName;
import cn.harmonyoslearn.navrouter.datas.NavrouterInfo;
import cn.harmonyoslearn.navrouter.models.NavrouterInfoModel;
import cn.harmonyoslearn.navrouter.models.ServiceModel;
import cn.harmonyoslearn.navrouter.utils.FileUtil;
import cn.harmonyoslearn.navrouter.utils.LogUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.*;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Objects;


public class FileUndoListener {
    private static FileUndoListener instance;

    public static FileUndoListener getInstance() {
        if (instance == null) {
            instance = new FileUndoListener();
        }
        return instance;
    }

    private FileUndoListener() {
    }

    private Boolean isSetupListeners = false;

    public void setupListeners(Project project) {
        if (isSetupListeners) {
            return;
        }
        isSetupListeners = true;

        // 监听文件系统的变化
        VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileAdapter() {
            @Override
            public void fileDeleted(@NotNull VirtualFileEvent event) {
                NavrouterInfo navrouterInfoMap = NavrouterInfoModel.getNavrouterInfoMap(project.getBasePath());
                if (!navrouterInfoMap.automaticDeletion) {
                    return;
                }

                // 文件被删除
                recordFileDeletion(event, project);
            }

            @Override
            public void fileCreated(@NotNull VirtualFileEvent event) {
                // 文件被创建，可能是 undo 操作导致的
                checkIfUndo(event);
            }
        });
    }

    private void recordFileDeletion(@NotNull VirtualFileEvent event, Project project) {
        String path = event.getFile().getPath();
        String basePath = project.getBasePath();
        // 记录文件删除事件
        LogUtil.i("FileUndoListener.recordFileDeletion", "File deleted: " + path);
        if (!isDeleteNavrouterPage(path, basePath)) {
            // 不是navrouter中的文件
            return;
        }

        try {
            ServiceModel.getInstance().deletePage(path);
        } catch (Exception e) {
            LogUtil.e("FileUndoListener.recordFileDeletion", e.getMessage());
        }
    }

    private void checkIfUndo(@NotNull VirtualFileEvent event) {
        // 检查是否为 undo 操作
        LogUtil.i("FileUndoListener.checkIfUndo", "File may be restored: " + event.getFile().getPath());
    }

    /**
     * 是否是Navrouter中的文件
     *
     * @param filePath 文件路径
     * @param basePath 项目根目录
     */
    private Boolean isDeleteNavrouterPage(String filePath, String basePath) {
        // 是否初始化navrouter
        String navrouterInfoPath = basePath + "/navrouter-info.json";
        if (!FileUtil.isFile(navrouterInfoPath)) {
            return false;
        }

        // 是否是文件
        if (!filePath.contains(".ets")) {
            return false;
        }

        // 是否在页面内
        String[] names = filePath.split("/");
        String name = names[names.length - 1];
        if (name != null) {
            ArrayList<NavName> navNames = null;
            try {
                navNames = ServiceModel.getInstance().getNavNamesModel().getNavNames();
            } catch (Exception e) {
                LogUtil.e("FileUndoListener.isDeleteNavrouterPage", e.getMessage());
            }

            if (navNames == null) {
                return false;
            }

            for (NavName navName : navNames) {
                if (Objects.equals(navName.name + ".ets", name)) {
                    return true;
                }
            }
        }
        return false;
    }
}
